package com.changgou.seckill.service.impl;

import com.changgou.entity.SeckillStatus;
import com.changgou.seckill.service.SeckillOrderService;
import com.changgou.seckill.task.MultiThreadingCreateOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * @author 戴金华
 * @date 2019-12-28 20:59
 */
@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {

    @Autowired
    private MultiThreadingCreateOrder multiThreadingCreateOrder;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 实现秒杀下单
     * @param time
     * @param id
     * @return
     */
    @Override
    public void add(String time, Long id, String username) {
        /**
         * 解决同一用户的重复排队问题
         * 记录用户的的排队次数
         * 1 key
         * 2 自增的值
         */
        Long userQueueCount = redisTemplate.boundHashOps("UserQueueCount").increment(username, 1);
        if (userQueueCount>1){
            //用户重复排队
           throw new RuntimeException("不允许重复下单");
        }

        //创建排队对象
        SeckillStatus seckillStatus = new SeckillStatus(username, new Date(), 1, id, time);
        //队列类型 用户抢单排队
        redisTemplate.boundListOps("SeckillOrderQueue").leftPush(seckillStatus);
        //hash类型 用于用户枪弹状态查询
        redisTemplate.boundHashOps("UserQueueStatus").put(username,seckillStatus);

        //异步执行抢单
        multiThreadingCreateOrder.createOrder();
    }

    /**
     * 用户抢单状态查询
     * @param username
     */
    @Override
    public SeckillStatus queryStatus(String username) {
        return (SeckillStatus) redisTemplate.boundHashOps("UserQueueStatus").get(username);
    }
}
